<template>
  <ContentWrap>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane :label="t('dataManage.LoginLog')" name="first">
        <el-form
          ref="formRef"
          :model="numberValidateForm"
          :inline="true"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item :label="t('dataManage.LogContent')" prop="logContent">
            <el-input

              v-model="numberValidateForm.logContent"
              type="text"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item :label="t('dataManage.CreateTime')" prop="date">
            <el-row>
              <el-col :span="24">
                <el-date-picker
                  :editable="false"
                  v-model="numberValidateForm.date"
                  type="daterange"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                  size="default"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm1(formRef)"
              ><Icon icon="ep:search" class="mr-5px" />{{ t('common.query') }}</el-button
            >
            <el-button @click="resetForm1(formRef)"
              ><Icon icon="ep:refresh-right" class="mr-5px" />{{ t('common.reset') }}</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 登录日志 -->
        <el-table
          ref="singleTableRef"
          :data="tableData"
          highlight-current-row
          style="width: 100%"
          @current-change="handleCurrentChange"
        >
          <el-table-column type="index" label="#" width="50" />
          <el-table-column
            property="logContent"
            :label="t('dataManage.LogContent')"
            width="220"
            sortable
          />
          <el-table-column property="userid" :label="t('dataManage.UserId')" width="120" sortable />
          <el-table-column property="username" :label="t('dataManage.UserName')" sortable />
          <el-table-column property="ip" label="ip" sortable />
          <el-table-column property="costTime" :label="t('dataManage.TimeConsuming')" sortable />
          <el-table-column property="logType_dictText" :label="t('dataManage.LogType')" sortable>
            <template #default="scope">
              <div v-if="scope.row.logType == 1"> 登录日志 </div>
            </template>
          </el-table-column>
          <el-table-column property="createTime" :label="t('dataManage.CreateTime')" sortable />
        </el-table>
        <!-- 分页 -->
        <el-pagination
          v-show="tableData.length > 0"
          v-model:current-page="pageLogin.currentPage"
          v-model:page-size="pageLogin.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageLogin.LoginTotal"
          @size-change="handleSizeChangeLogin"
          @current-change="handleCurrentChangePageLogin"
        />
      </el-tab-pane>
      <el-tab-pane :label="t('dataManage.OperationLog')" name="second">
        <el-form
          ref="ruleFormRefOperate"
          :inline="true"
          :model="ruleFormOperate"
          status-icon
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item :label="t('dataManage.SearchLog')" prop="logContent">
            <el-row>
              <el-col :span="24">
                <el-input

                  v-model="ruleFormOperate.logContent"
                  size="default"
                  autocomplete="off"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="t('dataManage.CreateTime')" prop="date">
            <el-row>
              <el-col :span="24">
                <el-date-picker
                  v-model="ruleFormOperate.date"
                  type="daterange"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                  size="default"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="t('dataManage.OperationType')" prop="region">
            <el-select v-model="ruleFormOperate.region" placeholder="please select your zone">
              <el-option :label="t('common.selectText')" value="" />
              <el-option
                v-for="item in selectOptions"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitFormOperate(ruleFormRefOperate)"
              ><Icon icon="ep:search" class="mr-5px" />{{ t('common.query') }}</el-button
            >
            <el-button @click="resetFormOperate(ruleFormRefOperate)"
              ><Icon icon="ep:refresh-right" class="mr-5px" />{{ t('common.reset') }}</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 表格 -->
        <el-table
          :data="tableDataOptions"
          :border="parentBorder"
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="expand">
            <template #default="props">
              <el-row>
                <el-col :span="24">
                  <p class="p1">请求方法: {{ props.row.username }}</p>
                </el-col>
                <el-col :span="24">
                  <p class="p2"><span></span>请求参数: {{ props.row.costTime }}</p>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#" width="50" />
          <el-table-column
            sortable
            :label="t('dataManage.LogContent')"
            prop="logContent"
            show-overflow-tooltip
          />
          <el-table-column sortable :label="t('dataManage.UserId')" prop="userid" />
          <el-table-column sortable :label="t('dataManage.UserName')" prop="username" />
          <el-table-column sortable label="IP" prop="ip" />
          <el-table-column
            sortable
            :label="t('dataManage.TimeConsuming')"
            prop="costTime"
            show-overflow-tooltip
          />
          <el-table-column sortable :label="t('dataManage.LogType')" prop="logType_dictText">
            <template #default="scope">
              <div v-if="scope.row.logType == 2"> 操作日志 </div>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            :label="t('dataManage.OperationType')"
            prop="operateType_dictText"
          />
          <el-table-column sortable :label="t('dataManage.CreateTime')" prop="createTime" />
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="pageOptions.currentPage"
          v-model:page-size="pageOptions.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageOptions.total"
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChangePage1"
        />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
// import { pageLogin, handleSizeChangeLogin, handleCurrentChangePageLogin } from './components/data'
import { getLogApi } from '@/api/datalog/index'
import { formatDate } from '@/utils/time'
import { vCheckVal } from '@/directives/checkVal'
import {
  ElButton,
  ElTabs,
  ElTabPane,
  TabsPaneContext,
  ElTable,
  ElTableColumn,
  ElCol,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  FormInstance,
  FormRules,
  ElPagination,
  ElDatePicker
} from 'element-plus'
const { t } = useI18n()
defineOptions({
  name: 'DataManage'
})

//tabs
const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab.props.name, event)
  tab.props.name == 'first' ? loginRequest() : optionsRequest()
}

//search 登录日志
const formRef = ref<FormInstance>()
// 登录日志
interface User {
  logContent?: string
  userid?: string
  username?: string
  ip?: string
  costTime?: string
  logType_dictText?: string
  createTime?: string
  operateType_dictText?: string
}
interface DataType {
  [index: number]: User
}
const currentRow = ref()
const singleTableRef = ref<InstanceType<typeof ElTable>>()

const handleCurrentChange = (val: User | undefined) => {
  currentRow.value = val
}
let tableData = ref<DataType>([])

// 登录日志接口数据
interface logType2 {
  // _t?: string | number
  logType: number | string
  column: string
  order: string
  field: string
  pageNo: number
  pageSize: number
  keyWord?: string
  createTime_begin?: string
  createTime_end?: string
}
let logTypeData = reactive<logType2>({
  logType: 1,
  column: 'createTime',
  order: 'desc',
  field: 'id,,,logContent,userid,username,ip,costTime,logType_dictText,createTime',
  pageNo: 1,
  pageSize: 10
})

const numberValidateForm = reactive({
  logContent: '',
  date: ''
})
const pageLogin = reactive({
  currentPage: 1,
  pageSize: 10,
  small: false,
  background: false,
  LoginTotal: 0
})
const handleSizeChangeLogin = (val: number) => {
  // console.log(`${val} items per page`)
  logTypeData.pageSize = val
  logTypeData.pageNo = 1
  loginRequest()
}
const handleCurrentChangePageLogin = (val: number) => {
  // console.log(`current page: ${val}`)
  logTypeData.pageNo = val
  loginRequest()
}
const submitForm1 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (numberValidateForm.logContent) {
        logTypeData.keyWord = numberValidateForm.logContent
      }
      if (numberValidateForm.date.length > 0) {
        ;[logTypeData.createTime_begin, logTypeData.createTime_end] = numberValidateForm.date
      }
      logTypeData.pageNo = 1
      loginRequest()
      // console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}
const resetForm1 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  ;[logTypeData.createTime_begin, logTypeData.createTime_end] = numberValidateForm.date
  logTypeData.keyWord = numberValidateForm.logContent
  loginRequest()
}
// 登录日志请求request
async function loginRequest() {
  let {
    result: { total, size, records, current }
  } = await getLogApi(logTypeData)
  logTypeData.pageNo = 1
  pageLogin.currentPage = current
  pageLogin.pageSize = size
  pageLogin.LoginTotal = total
  records.map((item) => {
    item.createTime = formatDate(item.createTime)
  })
  tableData.value = records
}
//search 操作日志
interface OperateType {
  // _t?: string | number
  logType: number | string
  column: string
  order: string
  field: string
  operateType: string
  pageNo: number
  pageSize: number
  keyWord?: string
  createTime_begin?: string
  createTime_end?: string
}
let OperateTypeData = reactive<OperateType>({
  logType: 2,
  operateType: '',
  column: 'createTime',
  order: 'desc',
  field: 'id,,,logContent,userid,username,ip,costTime,logType_dictText,createTime',
  pageNo: 1,
  pageSize: 10
})
const ruleFormRefOperate = ref<FormInstance>()
const ruleFormOperate = reactive({
  logContent: '',
  date: '',
  region: ''
})
const selectOptions = [
  { name: '查询', value: 1 },
  { name: '添加', value: 2 },
  { name: '修改', value: 3 },
  { name: '删除', value: 4 },
  { name: '导入', value: 5 },
  { name: '导出', value: 6 }
]
const submitFormOperate = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (ruleFormOperate.logContent) {
        OperateTypeData.keyWord = ruleFormOperate.logContent
      }
      if (ruleFormOperate.date.length > 0) {
        ;[OperateTypeData.createTime_begin, OperateTypeData.createTime_end] = ruleFormOperate.date
      }
      OperateTypeData.operateType = ruleFormOperate.region
      optionsRequest()
      // console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetFormOperate = (formEl: FormInstance | undefined) => {
  // console.log(formEl, 111)
  if (!formEl) return
  formEl.resetFields()
  OperateTypeData.operateType = ruleFormOperate.region
  ;[OperateTypeData.createTime_begin, OperateTypeData.createTime_end] = ruleFormOperate.date
  OperateTypeData.keyWord = ruleFormOperate.logContent
  optionsRequest()
}

//操作日志
const parentBorder = ref(false)
let tableDataOptions = ref([])
const pageOptions = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 1
})
// 操作日志请求request
async function optionsRequest() {
  let {
    result: { total, size, records, current }
  } = await getLogApi(OperateTypeData)
  OperateTypeData.pageNo = 1
  pageOptions.currentPage = current
  pageOptions.pageSize = size
  pageOptions.total = total
  records.map((item) => {
    item.createTime = formatDate(item.createTime)
    selectOptions.map((items) => {
      if (Number(items.value) === Number(item.operateType)) {
        item.operateType_dictText = items.name
      }
    })
  })
  tableDataOptions.value = records
}
const handleSizeChange1 = (val: number) => {
  OperateTypeData.pageSize = val
  OperateTypeData.pageNo = 1
  optionsRequest()
}
const handleCurrentChangePage1 = (val: number) => {
  OperateTypeData.pageNo = val
  optionsRequest()
}

onMounted(async () => {
  //登录日志默认请求
  await loginRequest()
})
</script>

<style lang="less" scoped>
@import './index.less';
</style>
